import axios, {AxiosRequestConfig, AxiosResponse} from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';
import store from '../store';
import router from '../router';


const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 6000,
});

// 请求拦截
request.interceptors.request.use( (config:AxiosRequestConfig) => {
  if(store.state.logged && store.state.token){
    config.headers = {
      Authorization : store.state.token
    }
  }
  return config;
})

// 响应拦截
request.interceptors.response.use((response:AxiosResponse) => {
  if(response.data.code === 1){
    MessagePlugin.warning(response.data.message);
    return;
  }
  if(response.data.code === 2){
    router.push({
      name: 'login'
    });
    localStorage.clear();
    MessagePlugin.warning(response.data.message);
  }
  return response.data;
}, (err: any) => {
  MessagePlugin.error(err);
});

export default request.request;
